###
	Outline
	
	- Global Vars
	- Core Code (run once)
		-- add empty table
		-- subscription
			-- couch view - get data
				-- parse data
				-- save parsed data into new data
			-- loop sorted new data and create table rows
			-- hide rows depending on organization or individual
			-- event handling on generated links
###

define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	$.fn.mb_search_result = (SamCtx) ->

	# --- Global Variables and Function ---------------

		$this = $(@)
		S = SamCtx
		$tpl = $('<tr>').html '
				<td class="col_id"><%= index %></td>
				<td class="col_name"><%= name %></td>
				<td class="col_org"><%= org_name %></td>
				<td class="col_addr"><%= address %></td>
				<td class="col_phone"><%= phone %></td>'		
		
	# --- Core code of plugin -------------------------
	
		unless @mb_plugin()
			@mb_plugin 'search_result'
			
			# Initialization
			$this.find('.content').append("
				<p> </p>
				<table class='results' style='width: 100%;'>
					<tbody>
						<tr style='text-align: left'>
							<th>Index</th>
							<th>Name</th>
							<th>Organization</th>
							<th>Address</th>
							<th>Phone</th>
						</tr>
					</tbody>
				</table>
				<hr>")
			$this.hide()
			
			
			# Main subscription	
			# _key is the query to be entered as key to couchdb view
			# _orgview is either "org" or "ind"
			$.subscribe "mb.query", (e, {search_term: _key, search_type: _orgview}) =>
				$this.find('h3').hide()
				
				# Show the plugin (search results) on first publish, or first search
				if $this.is(":hidden") then $this.show()

				# Get Couch view and return all the queried results
				$.couch.db("vcn-members").view 'app/search', {key: _key, success: (data) -> 
					resultlist = []
					
					# Remove all the table rows except the header (cleans out the table)
					$this.find('tr:not(:has(th))').remove()
					
					for i of data.rows
						# sh stands for short-hand to make this var shorter
						sh = data.rows[i].value
					
						# The _fields array is an array of all the properties in the json object retrieved to match against
						# in order to identify missing properties and fill them in with blank fields
						sh[k] or= "" for k in [	'tel_home', 
											'province', 
											'city', 
											'tel_work', 
											'tel_fax', 
											'org_name', 
											'tel_cell', 
											'postal_code', 
											'street_address', 
											'last_name', 
											'first_name'	]

						# Name column: Create concatenation for name in format LAST, FIRST
						_name = "#{sh.last_name.toCaps()}, #{sh.first_name.toCaps()}"
					
						# Phone column: Only display one number at a time. 
						_phone = ""
						_phone = "Fax: #{sh.tel_fax}" if sh.tel_fax isnt ""
						_phone = "Work: #{sh.tel_work}" if sh.tel_work isnt ""
						_phone = "Home: #{sh.tel_home}" if sh.tel_home isnt ""
					
						# Address column: Create concatenation string of the full address
						_addr = "#{sh.street_address.toCaps()} #{sh.city.toCaps()}, #{sh.province.toCaps()}, #{sh.postal_code.toUpperCase()}"
					
						# Give types (class names) for the rows depending on what that document is for subsequent hiding
						if sh.org then _type = "org" else _type = "ind"
						
						resultlist[i] = {
							_id : sh._id,
							name : _name,
							phone : _phone, 
							address : _addr,
							type : _type,
							org_name : sh.org_name.toCaps()
							}
				
					# Iterate through the newly defined object with the parsed properties and append them to table on the 
					# current page
					x = 0
					y = 0
					for j of resultlist.sort(H.sortby('name'))
						i = resultlist[j]
						if i.type is "org" then s = x++
						if i.type is "ind" then s = y++
						# Create the table rows
						content = S.content $tpl,
								index: Number(s) + 1
								name: i.name
								org_name: i.org_name
								address: i.address
								phone: i.phone
						$this.find('tbody')
							.append $('<tr>')
								.attr("id": i._id, "index": Number(j) + 1)
								.addClass(i.type)
								.append content	
							
					# Hide non-org rows and show the organization td cells if in organization view
					# Otherwise, show non-org rows and hide the organization td cells if in individual view
					if _orgview  is 'org'
						$('th:contains("Organization")').show()
						$('.org').show().find('.col_org').show()
						$('.ind').hide()
					else
						$('th:contains("Organization")').hide()
						$('.ind').show().find('.col_org').hide()
						$('.org').hide() 
					
					
					$this.find('tr:visible:eq(1)').trigger('mousedown')

					# Display number of results for current query
					# $this.find('table').prev('p').html("Found #{$('tr:not(:has(th)):visible').length} results for \"#{arg['raw_term']}\"")
					
					# Catch click events on the name links in this page and publish the appropriate donor_id
					# return false so the page doesn't actually change but let sammy handle that (need this?)
					$('a.donor_links').on 'click', ->
						$.publish 'mb.donor', {donor_id: @id}
						return	
					}

			$this.find('.results').on "mousedown", 'tr:not(:has(th))', ->
				$this.find('.results').addClass('focus') if $this.find('.selected').length isnt 0
				$this.find('.selected').removeClass('selected')
				$(@).addClass('selected')
				return

			$this.find('[name="view_donor"]').click () ->
				$.publish "mb.donor", {donor_id : $this.find('.selected').attr('id')}
				S.app.setLocation "#/donor_detail"

			$('[name="search_term"]').focus () ->
				$this.find('.results').removeClass('focus')

			$(document).on 'keydown', (e) ->
				if $this.find('.results').hasClass('focus')
					$('[name="search_term"]').blur()
				return if not $this.find('.results').hasClass('focus')
				
				switch e.keyCode
					# Keypress Down
					when 40
						$this.find('.selected').nextAll("tr:visible:eq(0)").trigger('mousedown')
						return false
					# Keypress Up
					when 38
						$this.find('.selected').prevAll('tr:visible:eq(0)').trigger('mousedown')
						return false
					# Keypress Up
					when 13
						$.publish "mb.donor", {donor_id : $this.find('.selected').attr('id')}
						S.app.setLocation "#/donor_detail"
						return false
					else
						return true

		return @
	return
